package com.example.campuscardmanagementsys;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import jakarta.servlet.http.HttpSession;
import java.sql.*;
import java.util.Map;

@RestController
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
@RequestMapping("/api/auth")
public class AuthController {

    // 获取数据库连接
    private Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/BlogSystem?useSSL=false&useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "111111";
        return DriverManager.getConnection(url, user, password);
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        String email = request.get("email");

        String checkSql = "SELECT * FROM Users WHERE Username = ?";
        String insertSql = "INSERT INTO Users (Username, Password, Email) VALUES (?, ?, ?)";

        try (Connection conn = getConnection();
             PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {

            checkStmt.setString(1, username);
            ResultSet rs = checkStmt.executeQuery();

            if (rs.next()) {
                return ResponseEntity.status(400).body("用户名已存在");
            }

            try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
                insertStmt.setString(1, username);
                insertStmt.setString(2, password);
                insertStmt.setString(3, email);
                insertStmt.executeUpdate();
            }

            return ResponseEntity.ok("注册成功");

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody Map<String, String> request, HttpSession session) {
        String username = request.get("username");
        String password = request.get("password");

        String sql = "SELECT * FROM Users WHERE Username = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                String dbPassword = rs.getString("Password");
                if (dbPassword.equals(password)) {
                    session.setAttribute("userId", rs.getInt("UserID"));
                    session.setAttribute("username", rs.getString("Username"));
                    session.setAttribute("role", rs.getString("Role"));
                    return ResponseEntity.ok("登录成功");
                } else {
                    return ResponseEntity.status(401).body("密码错误");
                }
            } else {
                return ResponseEntity.status(404).body("用户不存在");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

    // 用户登出
    @PostMapping("/logout")
    public ResponseEntity<String> logout(HttpSession session) {
        session.invalidate();
        return ResponseEntity.ok("已退出登录");
    }
}
